package com.liveneo.adapter.mobile.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.MapperWrapper;

/*******
 * XML文件处理类
 * 
 * @author Yubaode
 */
public class XMLProcessor {
	private static final Logger logger = Logger.getLogger(XMLProcessor.class);
	public static final String encoding = "UTF-8";

	public XMLProcessor() {
	}

	/************
	 * 将实体对象转成对应对的xml文件
	 * @param obj 实体类
	 * @param encoding 编码方式
	 * @return
	 */
	public static String toXml(Object obj, String encoding){
		try {
			XStream xstream = new XStream(new DomDriver(encoding));
			xstream.processAnnotations(obj.getClass()); // 识别obj类中的注解
			// 以格式化的方式输出XML
			return xstream.toXML(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/********
	 * 将传入xml文本转换成Java对象
	 * @param <T>
	 * @param xmlstring
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T toBean(String xmlstring, Class<T> cls) throws Exception {
		try {
			if (xmlstring == null) {
				throw new Exception("null String..");
			}
			XStream xstream = new XStream(new DomDriver());
			xstream.processAnnotations(cls);
			T t = (T) xstream.fromXML(xmlstring);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("解析失败：" + e.getMessage());
		}
	}

	/********
	 * 将传入xml文本转换成Java对象
	 * 
	 * @param <T>
	 * @param xmlstring
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T toBean(InputStream xmlin, Class<T> cls) throws Exception {
		try {
			if (xmlin == null) {
				throw new Exception("null String..");
			}
			XStream xstream = new XStream(new DomDriver());
			xstream.processAnnotations(cls);
			T t = (T) xstream.fromXML(xmlin);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("解析失败：" + e.getMessage());
		}
	}

	/********************
	 * 将传入xml文本转换输入流 再转 string
	 * 
	 * @param inputStream
	 *            xml字符串流
	 * @return
	 * @throws IllegalParameterException
	 */
	public static String xmlStringToInputStream(InputStream inputStream) throws Exception {
		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = inputStream.read(b, 0, 1024)) > 0) {
				out.write(b, 0, i);
			}
			byte[] req = out.toByteArray();
			String str = new String(req, "UTF-8");
			return str.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("解析失败：" + e.getMessage());
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/****
	 * 输出xml XML序列化
	 * 
	 * @param xStream
	 * @param m
	 */
	public static String outXML(XStream xStream, Object m) {
		// xStream.autodetectAnnotations(true);
		String xml = xStream.toXML(m);
		return xml;
	}

	/****
	 * XML反序列化
	 * @param xStream
	 * @param xml
	 */
	public static Object outBean(XStream xStream, String xml) {
		xStream.autodetectAnnotations(true);
		Object obj = xStream.fromXML(xml);
		return obj;
	}

	 /**
     * json格式转对象
     * @param jsonStr
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
	public static <T> T jsonToBean(String jsonStr,Class<T>... clazz){
    	T t = null;
    	XStream stream = new XStream(new JettisonMappedXmlDriver()){
    		@Override  
	        protected MapperWrapper wrapMapper(MapperWrapper next){  
	            return new MapperWrapper(next) {  
	                @SuppressWarnings("rawtypes")
					@Override  
	                public boolean shouldSerializeMember(Class definedIn, String fieldName) {  
	                    if(definedIn == Object.class){  
	                        try{  
	                            return this.realClass(fieldName)!=null;  
	                        }catch(Exception e){  
	                            return false;  
	                        }  
	                    }  
	                    return super.shouldSerializeMember(definedIn, fieldName);  
	                }  
	            };  
	        }  
    	};
    	stream.setMode(XStream.NO_REFERENCES);  
    	stream.processAnnotations(clazz);  
    	t = (T)stream.fromXML(jsonStr);  
    	return t;
    }
    
    /**
     * 对象转json格式数据
     * @param obj
     * @return
     */
    public static String beanToJson(Object obj){
    	String jsonStr = "";
    	if(!StringUtils.isEmpty(obj.toString())){
	    	XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
	        xstream.setMode(XStream.NO_REFERENCES);
	        xstream.processAnnotations(obj.getClass()); 
	        jsonStr = xstream.toXML(obj);
    	}
        return jsonStr;
    }
	
	public static void main(String[] args) throws Exception {
		// jsontoBean();
		// testData();
		// returnData();
		testXmlToBean();
	}
	public static void testXmlToBean(){
	/*	String xml="<records><record><t_sample>2011-11-18 14:30:00.0</t_sample><dialognum>0</dialognum>"
				+ "<nettype>0</nettype><service>0</service><moduleno>133</moduleno>"
				+ "</record><record><t_sample>2011-11-18 14:30:30.0</t_sample>"
				+ "<dialognum>0</dialognum><nettype>0</nettype><service>0</service>"
				+ "<moduleno>133</moduleno></record></records>";
		XStream xstream= new XStream(new DomDriver());
		xstream.autodetectAnnotations(true);
		xstream.alias("records",List.class);
		xstream.alias("record",Record.class);
		List<Record> listRequest=(List<Record>) xstream.fromXML(xml);
		System.out.println(listRequest.size());*/
	}
	
	
	// public static void returnData(){
	// RepairResponse response=new RepairResponse();
	// RepairResponseHead responseHead=new RepairResponseHead();
	// RepairResponseDetails responseDetails=new RepairResponseDetails();
	// List<GarageResult> garageResultList= new ArrayList<GarageResult>();
	//
	// for (int i = 0; i < 2; i++) {
	// GarageResult garageResult=new GarageResult();
	// garageResult.setGarageCode("修理厂代码");
	// garageResult.setErrorMessage("错误信息");
	// garageResult.setResultCode("返回代码 0成功 1失败");
	// garageResultList.add(garageResult);
	// }
	//
	// responseHead.setServiceCode("当前系统服务编号");
	// responseHead.setServiceName("当前系统服务名称");
	// responseHead.setInterfaceCode("接口编号");
	// responseHead.setInterfaceName("接口名称");
	// responseHead.setSendCode("数据发送方编号");
	// responseHead.setSendName("数据发送方名称");
	// responseHead.setUsrSignature("用户签名");
	// responseHead.setPassword("加密数据");
	// responseHead.setDateTime("发送时间（时间戳）");
	// responseHead.setDateTime(String.valueOf(System.currentTimeMillis()));
	//
	// responseDetails.setGarageResult(garageResultList);
	// response.setResponseHead(responseHead);
	// response.setResponseDetails(responseDetails);
	//
	// //Bean 转JSON 正确
	// XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
	// xstream.autodetectAnnotations(true);
	// xstream.alias("repairResponse",RepairResponse.class);
	// xstream.alias("garageInfo",GarageInfo.class);
	// String requestGarageJSON=outXML(xstream,response);
	// System.out.println("JavaBean->json:"+requestGarageJSON);
	// }
	//
	// public static void testData(){
	// RepairRequest requestGarage=new RepairRequest();
	// RepairRequestHead requestHead=new RepairRequestHead();
	// RepairRequestDetails repairRequestDetails=new RepairRequestDetails();
	// List<GarageInfo> repairRequestDetailsList=new ArrayList<>();
	// for (int i = 0; i < 2; i++) {
	//
	// GarageInfo garageInfo=new GarageInfo();
	// garageInfo.setGarageCode("修理厂代码");
	// garageInfo.setGarageName("修理厂名称");
	// garageInfo.setGarageAbbr("修理厂简称");
	// garageInfo.setGarageAddr("修理厂地址");
	// garageInfo.setLatitude("纬度");
	// garageInfo.setLongitude("经度");
	// garageInfo.setCompanyCode("公司代码");
	// garageInfo.setOrgCode("组织机构代码");
	// garageInfo.setIndustryOrgCode("注册机构代码");
	// garageInfo.setContact("联系人");
	// garageInfo.setContactPhone("联系电话");
	// garageInfo.setFax("传真");
	// garageInfo.setRepairLevel("修理厂级别");
	// garageInfo.setCategoryCode("修理厂级别代码");
	// garageInfo.setCategoryName("修理厂类别名称");
	// garageInfo.setDirectPayFlag("是否委托直赔");
	// garageInfo.setPartDiscountPercent("配件折扣率");
	// garageInfo.setPaintFacmanHour("喷漆单价商用车");
	// garageInfo.setRepairFacmanHour("钣金单价商用车");
	// garageInfo.setAssemblyFacmanHour("拆装单价商用车");
	// garageInfo.setDiscountStandard("工时标准费");
	// garageInfo.setRepairFacmanDiscount("钣金折扣率");
	// garageInfo.setPaintFacmanDiscount("喷漆折扣率");
	// garageInfo.setAssemblyFacmanDiscount("拆装折扣率");
	// garageInfo.setMachineRepairDiscount("机修折扣率");
	// garageInfo.setElectricanDiscount("电工折扣率");
	// garageInfo.setEvalFloatRatio("定损用管理费率");
	// garageInfo.setAuditRatio("审核通过的管理费率");
	// garageInfo.setCompensateIndex("目标赔付率指标");
	// garageInfo.setContractDate("合同有效期");
	// garageInfo.setRepair4sFlag("4S店标志");
	// garageInfo.setOutsideFlag("是否专修厂");
	// garageInfo.setCptFlag("是否维修合作");
	// garageInfo.setPrice4SCode("有无4S店价权限");
	// garageInfo.setPriceAgreementCode("有无协议价权限");
	// garageInfo.setPriceMarkCode("有无市场价权限");
	// garageInfo.setPriceTryoutCode("有无适用价权限");
	// garageInfo.setPlatformOrgCode("平台修理厂编码");
	// garageInfo.setVideoFlag("是否视频定损");
	// garageInfo.setRepairTel("视频定损设备号");
	// garageInfo.setRepairScope("修理资质及范围");
	// garageInfo.setSpecializedBrand("专修品牌");
	// garageInfo.setAuditOpinion("审核意见");
	// garageInfo.setRemark("描述说明");
	// garageInfo.setAccountCode("开户行账号代码");
	// garageInfo.setAccountName("开户行账号");
	// garageInfo.setBankName("开户行名称");
	// garageInfo.setCityCode("县编码");
	// garageInfo.setTownCode("市编码");
	// garageInfo.setRegionCode("省编码");
	// garageInfo.setCityName("县名称");
	// garageInfo.setTownName("市名称");
	// garageInfo.setRegionName("省名称");
	// garageInfo.setBrandCode("品牌编码");
	// garageInfo.setBrandName("品牌名称");
	// garageInfo.setBrandPercent("品牌折扣");
	// garageInfo.setAtticePointCode("网点代码");
	// garageInfo.setAtticePointName("网点名称");
	// garageInfo.setPartsPercent("配件折扣率");
	// garageInfo.setVerifyFlag("流程状态");
	// garageInfo.setVerifyBy("审核人");
	// garageInfo.setVerifyDate("审核时间");
	// garageInfo.setStatus("状态");
	// repairRequestDetailsList.add(garageInfo);
	// }
	//
	//
	//
	// requestHead.setServiceCode("当前系统服务编号");
	// requestHead.setServiceName("当前系统服务名称");
	// requestHead.setInterfaceCode("接口编号");
	// requestHead.setInterfaceName("接口名称");
	// requestHead.setSendCode("数据发送方编号");
	// requestHead.setSendName("数据发送方名称");
	// requestHead.setUsrSignature("用户签名");
	// requestHead.setPassword("加密数据");
	// requestHead.setDateTime("发送时间（时间戳）");
	// requestHead.setDateTime(String.valueOf(System.currentTimeMillis()));
	//
	// repairRequestDetails.setGarageInfo(repairRequestDetailsList);
	// requestGarage.setRequestDetails(repairRequestDetails);
	// requestGarage.setRequestHead(requestHead);
	//
	//
	// XStream xstream = new XStream();
	//// xstream.autodetectAnnotations(true);
	//// //Bean 转 XML正确
	//// xstream.alias("repairRequest",RepairRequest.class);
	//// xstream.alias("garageInfo",GarageInfo.class);
	//// String xml=outXML(xstream,requestGarage);
	//// System.out.println("Bean->xml:"+xml);
	//
	// //Bean 转JSON 正确
	// xstream = new XStream(new JsonHierarchicalStreamDriver());
	// xstream.autodetectAnnotations(true);
	// xstream.alias("repairRequest",RepairRequest.class);
	// xstream.alias("garageInfo",GarageInfo.class);
	// xstream.ignoreUnknownElements("garageId");
	// String requestGarageJSON=outXML(xstream,requestGarage);
	// System.out.println("JavaBean->json:"+requestGarageJSON);
	//
	// //XML 转 Bean
	//// xstream= new XStream(new DomDriver());
	//// xstream.autodetectAnnotations(true);
	//// xstream.alias("repairRequest",RepairRequest.class);
	//// xstream.alias("garageInfo",GarageInfo.class);
	//// RepairRequest repairRequest=(RepairRequest) xstream.fromXML(xml);
	//// System.out.println("xml->JavaBean:"+repairRequest.getRequestDetails().getGarageInfo().get(0).getGarageCode());
	//
	// //JSON 转 JavaBean
	//// xstream = new XStream(new JettisonMappedXmlDriver());
	//// xstream.autodetectAnnotations(true);
	//// xstream.alias("repairRequest",RepairRequest.class);
	//// xstream.alias("garageInfo",GarageInfo.class);
	//// RepairRequest repairRequestJSON=(RepairRequest)
	// xstream.fromXML(requestGarageJSON);
	//// System.out.println("json->JavaBean:"+repairRequestJSON.getRequestDetails().getGarageInfo().get(0).getGarageCode());
	////
	// //JSON 转XML 正确
	//// xstream = new XStream();
	//// xstream.autodetectAnnotations(true);
	//// xstream.alias("repairRequest",RepairRequest.class);
	//// xstream.alias("garageInfo",GarageInfo.class);
	//// String json= outXML(xstream,repairRequestJSON);
	//// System.out.println("json->xml"+json);
	// }
	//
	// public static void jsontoBean(){
	// String json="{\"repairResponse\":{\"responseDetails\": {\"garageInfo\":
	// {\"resultCode\": \"0\",\"errorMessage\":\"处理成功\","
	// + "\"garageCode\": \"10001\"}},\"responseHead\": {\"serviceCode\":
	// \"ET\",\"serviceName\": \"ET系统\","
	// + "\"interfaceName\": \"修理厂数据推送给ET\",\"sendCode\": \"\",\"sendName\":
	// \"\",\"usrSignature\": \"\",\"password\": \"\",\"dateTime\":
	// \"1469169112904\"}}}";
	// System.out.println("JSON:"+json);
	// XStream xstream = new XStream(new JettisonMappedXmlDriver());
	// xstream.autodetectAnnotations(true);
	// xstream.alias("repairResponse",RepairResponse.class);
	// xstream.alias("garageResult",GarageResult.class);
	//// xstream.
	// RepairResponse response=(RepairResponse) xstream.fromXML(json);
	// System.out.println("response:"+response.getResponseHead().getDateTime());
	// }

}